import { PureComponent } from "react";
import { SearchBar,Carousel,Grid,Flex,TabBar,Button,PullToRefresh,ListView} from "antd-mobile"
import { ActivityIndicator } from 'antd-mobile';
import { connect } from 'dva';
import { Row, Col,Select } from 'antd';
import ReactDOM from 'react-dom';
import { handleImg, goToPage,isNull,handleOSS } from "../../utils/helper";
import {IntlProvider, addLocaleData,FormattedMessage} from 'react-intl';
import localeData from '../../../public/lang/data.json';
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
import MToast from '../../components/Util/MToast';
const Option = Select.Option;
const NUM_ROWS = 20;
let pageIndex = 0;

function genData(pIndex = 0) {
  const dataArr = [];
  for (let i = 0; i < NUM_ROWS; i++) {
    consolelog()
    dataArr.push(`row - ${(pIndex * NUM_ROWS) + i}`);
  }
  return dataArr;
}

@connect(() => {
  return ({

  })
})
export default class MelaShop extends PureComponent{
  constructor(props){
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });
    this.state = {
      carouselItem:[],
      loading:true,
      dataSource,
      height: document.documentElement.clientHeight * 3 / 4,
      isLoading: true,
      refreshing: true,
      selectedTab: 'redTab',
      onImg:true,
      locale:'it',
      isOption:false,
      data:[],
    }
  }
  componentDidMount() {

    setTimeout(() => {
      this.rData = genData();
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(genData()),
        refreshing: false,
        isLoading: false,
      });
    }, 1500);
  }
  componentWillMount(){
    let {dispatch,location} = this.props;
this.bannerList();
 this.goodContent();
    if(localStorage.locale=='it'){
      this.setState({
        locale:'it',
        isOption:false
      })
    }else if(localStorage.locale=='zh'){
      this.setState({
        locale:'zh',
        isOption:true
      })
    }else{
      localStorage.setItem("locale",'it')
      this.setState({
        locale:'it',
        isOption:false
      })
    }

  }
  bannerList(){
    let {dispatch,location} = this.props;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "qry/all?_c=app_banner_list",
          params: [
          ],
          _c: "app_banner_list"
        },
        callback: (result) => {
          let { data } = result;
          this.setState({
            carouselItem:data,
            loading:false,

          })
          console.log(data)

        }
      }
    });
  };
  goodContent(){
    let {dispatch,location} = this.props;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "lv/data?_c=app_goods_page_list",
          params: [
            {
              key: "page_index",
              value: 1
            },
            {
              key: "page_size",
              value: 20
            },
          ],
          _c: "app_goods_page_list"
        },
        callback: (result) => {
          let { data } = result;
          console.log(data.list);
          console.log(data.list[0].store_id)
          localStorage.setItem("store_id",data.list[0].store_id)
          this.setState({
            data:data.list
          })
        }
      }
    });
  }
  goodList() {
    let { dataSource} = this.state;

    if (!dataSource || dataSource.length == 0) {
      return (
        <div style={{ padding: "40px 0", textAlign: "center", fontSize: "20px", color: "#555" }}>
          {T(localeData[localStorage.locale].goodsDetailCartNoGood)}
        </div>
      )
    }
    else {
      let contents = [];
      return (
        <div className="box" style={{height:'100%',paddingBottom:'20%'}}>
          {dataSource.map((i,k) => (
            <div  key={k} style={{background:'#fff',fontWeight:'bold',padding:'5% 5% 5%',borderRadius:'10px'}} className="item">
              <div onClick={(e)=>{this.handleDetail(e,i)}}>
                <img src={handleOSS(i.img_url)} style={{width:'100%',height:'100%'}}/>
              </div>
              <div style={{overflow:'hidden',margin:'10% 0px 0px'}}>
                <p className="ellipsis2" style={{margin:'12px 0px 0px',textAlign:'left',color:'#595867',fontSize:'13px',}}>{i.goods_name}</p>
                <div style={{overflow:'hidden',marginTop:'8px'}}>
                  <div style={{float:'left',color:'#F09600',fontSize:'15px',marginTop:'5px'}}>€{i.price}</div>
                  <div style={{float:'right',width:'34px',height:'34px'}} onClick={(e) => {this.handleAdd(e,i) }}>
                    <img src="image/cart1.png" style={{width:'32px',height:'32px'}}/>
                  </div>
                </div>

              </div>

              {/*<Button type="primary" size="small" inline style={{marginBottom:'1em'}} onClick={(e) => {this.handleAdd(e,i) }}>+ADD</Button>*/}
            </div>

          ))}
        </div>

      )
    }
  }
  handleDetail=(e,i)=>{
    let {dispatch} = this.props;
    goToPage({ dispatch, config: { url: "/goodsDetail?id="+i.id+"&store_id="+i.store_id }, isReplace: false })
  }
  handleAdd=(e,i)=>{
    // console.log(i);
    let {dispatch} = this.props;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "cart/add",
          params: [
            {
              key: "goods_id",
              value: i.id
            },
            {
              key: "goods_name",
                value: i.goods_name
            },
            {
              key: "img_url",
                value: i.img_url
            },
            {
              key: "price",
                value: i.price
            },
            {
              key: "quantity",
                value: 1
            }
          ]
        },
        callback: (result) => {
          let { data } = result;
       console.log(data)
            MToast.info(T(localeData[localStorage.locale].goodsDetailCartInfo,3, null, false));

        }
      }
    })
  }
  chooseLocale=(value)=>{
    const {locale}=this.state;
    // // const localeValue = value;
    localStorage.setItem("locale",value)
    this.setState({
      locale: value,
      onImg:false
    });
    console.log(value);
  }
  onRefresh=()=>{
    this.bannerList();
    this.goodContent();
  }
  // 滑动到底部时加载更多
  onEndReached = (event) => {
    // load new data
    // hasMore: from backend data, indicates whether it is the last page, here is false
    if (this.state.isLoading && !this.state.hasMore) {
      return;
    }
    console.log('reach end', event);
    this.setState({ isLoading: true });

      this.rData = [...this.rData, ...genData(++pageIndex)];
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(this.rData),
        isLoading: false,
      });

  };
  render(){
    let {dispatch} = this.props;
    let {carouselItem,dataSource,dataSourceObj,loading,onImg,isOption,data} = this.state;
    const messages = localeData[localStorage.locale]
    console.log(this.state.locale,isOption)
    const separator = (sectionID, rowID) => (
      <div
        key={`${sectionID}-${rowID}`}

      />
    );
    let index = data.length - 1;
    const row = (rowData, sectionID, rowID) => {
      if (index < 0) {
        index = data.length - 1;
      }
      const obj = data[index--];
      console.log(obj)
      return (
        <div style={{marginBottom:'6%'}}>
          <div  key={rowID} style={{background:'#fff',fontWeight:'bold',padding:'5% 5% 5%',borderRadius:'10px'}} className="item">
            <div onClick={(e)=>{this.handleDetail(e,obj)}}>
              <img src={handleOSS(obj.img_url)} style={{width:'100%',height:'100%'}}/>
            </div>
            <div style={{overflow:'hidden',margin:'10% 0px 0px'}}>
              <p className="ellipsis2" style={{margin:'12px 0px 0px',textAlign:'left',color:'#595867',fontSize:'13px',}}>{obj.goods_name}</p>
              <div style={{overflow:'hidden',marginTop:'8px'}}>
                <div style={{float:'left',color:'#F09600',fontSize:'15px',marginTop:'5px'}}>€{obj.price}</div>
                <div style={{float:'right',width:'34px',height:'34px'}} onClick={(e) => {this.handleAdd(e,obj) }}>
                  <img src="image/cart1.png" style={{width:'32px',height:'32px'}}/>
                </div>
              </div>

            </div>

            {/*<Button type="primary" size="small" inline style={{marginBottom:'1em'}} onClick={(e) => {this.handleAdd(e,i) }}>+ADD</Button>*/}
          </div>


        </div>
      );
    };


    if (loading) {
      return (
        <div className="normal">
          <ActivityIndicator toast text="正在加载" animating={true} />
        </div>
      )
    }
    return(
      <div style={{background:'rgb(249, 247, 247)'}}>
        <IntlProvider
          locale={ this.state.locale } messages={messages}
        >
          <div>
            {isOption?
              <div >
                {/*{onImg?<img src="image/china.png" style={{position:'fixed',top:'3%',left:'2%',zIndex:'100',width:'16px',height:'16px'}}/>:''}*/}
                <Select
                defaultValue="zh"
                onChange={this.chooseLocale}
                bordered={false}
                style={{position:'fixed',top:'3%',left:'4%',zIndex:'200',width:'20%',}}
              >
                {/*<Option key="cn" value="en">English</Option>*/}
                <Option  key="it" value="it">
                  <div className="demo-option-label-item" style={{fontSize:'12px'}}>
                  <span role="img" aria-label="IT">
                    <img src="image/Italy.png" style={{width:'16px',height:'16px',marginRight:'3px'}}/>
                  </span>
                    IT
                  </div>
                </Option>
                <Option  key="en" value="zh" >
                  <div className="demo-option-label-item" style={{fontSize:'12px'}}>
                  <span role="img" aria-label="ZH">
                    <img src="image/china.png" style={{width:'16px',height:'16px',marginRight:'3px'}}/>
                  </span>
                    CN
                  </div>
                </Option>

              </Select>
              </div>:
              <div>
                {/*{onImg?<img src="image/Italy.png" style={{position:'fixed',top:'3%',left:'2%',zIndex:'100',width:'16px',height:'16px'}}/>:""}*/}
                <Select
                  defaultValue="it"
                  onChange={this.chooseLocale}
                  bordered={false}
                  style={{position:'fixed',top:'3%',left:'4%',zIndex:'200',width:'20%',}}
                >
                  {/*<Option key="cn" value="en">English</Option>*/}
                  <Option  key="it" value="it">
                    <div className="demo-option-label-item" style={{fontSize:'12px'}}>
                  <span role="img" aria-label="IT">
                    <img src="image/Italy.png" style={{width:'16px',height:'16px',marginRight:'3px'}}/>
                  </span>
                      IT
                    </div>
                  </Option>
                  <Option  key="en" value="zh" >
                    <div className="demo-option-label-item" style={{fontSize:'12px'}}>
                  <span role="img" aria-label="ZH">
                    <img src="image/china.png" style={{width:'16px',height:'16px',marginRight:'3px'}}/>
                  </span>
                      CN
                    </div>
                  </Option>

                </Select>
              </div>
            }


          <div maxLength={8} style={{position:'fixed',top:'2%',left:'3%',width:'92%',zIndex:'100',height:'44px',border:'1px solid #ddd',borderRadius:'15px',background:"#fff"}} onClick={()=>{goToPage({ dispatch, config: { url: "/searchPage" }, isReplace: false })}}>
            <div style={{position:'absolute',top:'25%',left:'37%'}}>
              <img src="image/search_24px.png" style={{width:'24px',height:'24px'}}/><span style={{color:'#C9C9C9',fontSize:'13px'}}>{messages.searchPlaceholder}</span>
            </div>
          </div>
          </div>
          <PullToRefresh
            damping={100}
            onRefresh={this.onRefresh}
          >
          <Carousel
            autoplay={true}
            infinite
            autoplayInterval={10000}
            speed={400}
          >
            {this.state.carouselItem.map((i,k) => (
              <a
                key={k}
                style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
              >
                <img
                  src={handleOSS(i.url)}
                  alt=""
                  style={{ width: '100%', verticalAlign: 'top',height:'237px' }}
                  onLoad={() => {
                    // fire window resize event to change height
                    this.setState({ imgHeight: '237px' });
                  }}
                />
              </a>
            ))}
          </Carousel>
          <p style={{color:'#2E2D35',fontSize:'17px',margin:'16px 16px 0px'}}>Più venduti</p>
            <ListView
              ref={el => this.lv = el}
              dataSource={this.state.dataSource}
              renderRow={row}
              renderSeparator={separator}
              useBodyScroll
              onEndReachedThreshold={10}
              renderFooter={() => (<div style={{ padding: 30, textAlign: 'center' }}>
                {this.state.isLoading ? 'Loading...' : 'Loaded'}
              </div>)}
              onEndReached={this.onEndReached}
              pageSize={5}
              // className="box"
              style={{
                height:'100%',
                paddingBottom:'20%',
              }}
            >

            </ListView>
          {/*{this.goodList()}*/}
          </PullToRefresh>
          <div style={{position:'fixed',bottom:'0px',left:'0px',width:'100%'}}>
            <TabBar
              unselectedTintColor="#949494"
              tintColor="#F09600"
              barTintColor="white"
              hidden={this.state.hidden}
            >
              <TabBar.Item
                title={messages.home}
                key="Life"
                icon={<div style={{
                  width: '24px',
                  height: '24px',
                  background: 'url(image/home2.png) center center /  21px 21px no-repeat' }}
                />
                }
                selectedIcon={<div style={{
                  width: '24px',
                  height: '24px',
                  background: 'url(image/home3.png) center center /  21px 21px no-repeat' }}
                />
                }
                selected={this.state.selectedTab === 'redTab'}
                onPress={() => {
                  this.setState({
                    selectedTab: 'redTab',
                  });
                  goToPage({ dispatch, config: { url: "/shop_home" }, isReplace: false })
                }}
                data-seed="logId"
              >

              </TabBar.Item>
              <TabBar.Item
                icon={
                  <div style={{
                    width: '24px',
                    height: '24px',
                    background: 'url(image/category.png) center center /  21px 21px no-repeat' }}
                  />
                }
                selectedIcon={
                  <div style={{
                    width: '24px',
                    height: '24px',
                    background: 'url(image/category1.png) center center /  21px 21px no-repeat' }}
                  />
                }
                title={messages.category}
                key="Koubei"

                selected={this.state.selectedTab === 'blueTab'}
                onPress={() => {
                  this.setState({
                    selectedTab: 'blueTab',
                  });
                  goToPage({ dispatch, config: { url: "/category" }, isReplace: false })
                }}
                data-seed="logId1"
              >

              </TabBar.Item>
              <TabBar.Item
                icon={
                  <div style={{
                    width: '24px',
                    height: '24px',
                    background: 'url(image/cart4.png) center center /  21px 21px no-repeat' }}
                  />
                }
                selectedIcon={
                  <div style={{
                    width: '24px',
                    height: '24px',
                    background: 'url(image/cart5.png) center center /  21px 21px no-repeat' }}
                  />
                }
                title={messages.cart}
                key="Friend"
                selected={this.state.selectedTab === 'greenTab'}
                onPress={() => {
                  this.setState({
                    selectedTab: 'greenTab',
                  });
                  goToPage({ dispatch, config: { url: "/goodcart" }, isReplace: false })
                }}
              >
              </TabBar.Item>
              <TabBar.Item
                icon={{ uri: 'image/my.png' }}
                selectedIcon={{ uri: 'image/my1.png' }}
                title={messages.my}
                key="my"
                selected={this.state.selectedTab === 'yellowTab'}
                onPress={() => {
                  this.setState({
                    selectedTab: 'yellowTab',
                  });
                  goToPage({ dispatch, config: { url: "/my" }, isReplace: false })
                }}
              >
              </TabBar.Item>
            </TabBar></div>
        </IntlProvider>


      </div>
    )
  }
}
